package httpCtrler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-xorm/xorm"
	st "kjjcgroup_server/model"
	sv "kjjcgroup_server/service"
	"net/http"
	"strconv"
	"time"
)

func NewsRouter(router *gin.Engine, routerAuth *gin.RouterGroup) {
	router.GET("/news", news)
	LogMap["/news"] = "分页新闻列表"
	router.GET("/newsList", newsList)
	LogMap["/news"] = "新闻列表"
	routerAuth.PUT("/newsAdd", newsAdd)
	LogMap["/newsAdd"] = "添加新闻"
	routerAuth.PUT("/newsEdit", newsEdit)
	LogMap["/newsEdit"] = "编辑新闻"
	routerAuth.DELETE("/newsDel", newsDel)
	LogMap["/newsDel"] = "删除新闻"

	router.GET("/newsType", newsType)
	LogMap["/newsType"] = "查询新闻分类,检测是否有登录权限"
	routerAuth.PUT("/newsTypeAdd", newsTypeAdd)
	LogMap["/newsTypeAdd"] = "添加新闻分类"
	routerAuth.PUT("/newsTypeEdit", newsTypeEdit)
	LogMap["/newsTypeEdit"] = "编辑新闻分类"
	routerAuth.DELETE("/newsTypeDel", newsTypeDel)
	LogMap["/newsTypeDel"] = "删除新闻分类"
}

func news(c *gin.Context) {
	NewsId := c.Query("NewsId")
	Keyword := c.Query("Keyword")
	TypeId := c.Query("TypeId")
	Recommend := c.Query("Recommend")
	pageIdx, pageCnt := Page(c)
	if pageIdx == -1 {
		pageIdx = 0
	}
	if pageCnt == -1 {
		pageCnt = 10
	}
	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(409, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(true)
	var collArr []*st.News
	var collArr1 []*st.News
	var count int64
	if NewsId != "" {
		err = mysql.Where("news_id=?", NewsId).Find(&collArr)
		_, _ = mysql.Where("news_id=?", NewsId).Update(&st.News{ClicksNumber: collArr[0].ClicksNumber + 1})
		c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: collArr})
		return
	} else if Recommend != "" {
		err = mysql.Where("recommend=?", Recommend).Limit(pageCnt, pageIdx*pageCnt).Find(&collArr)
		count, _ = mysql.Where("recommend=?", Recommend).FindAndCount(&collArr1)
	} else if Keyword != "" {
		err = mysql.Where("news_title LIKE ?", "%"+Keyword+"%").Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArr)
		count, _ = mysql.Where("news_title LIKE ?", "%"+Keyword+"%").FindAndCount(&collArr1)
	} else if TypeId != "" {
		err = mysql.Where("type_id LIKE ?", "%"+TypeId+"%").Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArr)
		count, _ = mysql.Where("type_id LIKE ?", "%"+TypeId+"%").FindAndCount(&collArr1)
	} else {
		err = mysql.Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArr)
		count, _ = mysql.FindAndCount(&collArr1)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	rtnDt := rtnData(count, pageCnt, pageIdx, collArr)
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: rtnDt})

}

func newsList(c *gin.Context) {
	NewsId := c.Query("NewsId")
	Keyword := c.Query("Keyword")
	TypeId := c.Query("TypeId")
	Recommend := c.Query("Recommend")

	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(409, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(true)
	var collArr []*st.News
	if NewsId != "" {
		err = mysql.Where("news_id=?", NewsId).Find(&collArr)
		_, _ = mysql.Where("news_id=?", NewsId).Update(&st.News{ClicksNumber: collArr[0].ClicksNumber + 1})
		c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: collArr})
		return
	} else if Recommend != "" {
		err = mysql.Where("recommend=?", Recommend).Find(&collArr)
	} else if Keyword != "" {
		err = mysql.Where("news_title LIKE ?", "%"+Keyword+"%").OrderBy("create_time desc").Find(&collArr)
	} else if TypeId != "" {
		err = mysql.Where("type_id LIKE ? and recommend=?", "%"+TypeId+"%", 1).OrderBy("create_time desc").Find(&collArr)
	} else {
		err = mysql.OrderBy("create_time desc").Find(&collArr)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: collArr})

}

func newsAdd(c *gin.Context) {
	resDt := &st.News{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)
	mysql, err := sv.GetEngine()
	mysql.ShowSQL(true)
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	mysql.ShowSQL(true)

	err = sess.Begin()
	if err != nil {
		return
	}
	t := time.Now()
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	_, err = sess.Cols("type_id", "news_title", "news_img", "news_description", "news_content", "recommend", "user_account", "clicks_number", "create_time", "update_time").InsertOne(&st.News{TypeId: resDt.TypeId, NewsTitle: resDt.NewsTitle, NewsImg: resDt.NewsImg, NewsDescription: resDt.NewsDescription, NewsContent: resDt.NewsContent, Recommend: resDt.Recommend, UserAccount: resDt.UserAccount, ClicksNumber: resDt.ClicksNumber, CreateTime: t, UpdateTime: t})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "添加成功!"})
}

func newsEdit(c *gin.Context) {
	resDt := &st.News{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	mysql.ShowSQL(true)
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return
	}
	_, err = sess.Where("news_id=?", resDt.NewsId).Update(&st.News{TypeId: resDt.TypeId, NewsTitle: resDt.NewsTitle, NewsImg: resDt.NewsImg, NewsDescription: resDt.NewsDescription, NewsContent: resDt.NewsContent, UserAccount: resDt.UserAccount, ClicksNumber: resDt.ClicksNumber})
	_, err = sess.Where("news_id=?", resDt.NewsId).Cols("recommend").Update(&st.News{Recommend: resDt.Recommend})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "NewsId:" + strconv.Itoa(resDt.NewsId) + " 编辑成功!"})
}

func newsDel(c *gin.Context) {
	NewsId := c.Query("NewsId")
	mysql, err := sv.GetEngBom()
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	mysql.ShowSQL(true)
	_, err = mysql.Where("news_id=?", NewsId).Delete(&st.News{})
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "Failed", Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "NewsId:" + NewsId + " 删除成功!"})
}

func newsType(c *gin.Context) {
	typeId := c.Query("tyeId")
	parentId := c.Query("parentId")
	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(409, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(true)

	var collArr []*st.NewsType
	if typeId != "" {
		err = mysql.Where("type_id=?", typeId).Find(&collArr)
	} else if parentId != "" {
		err = mysql.Where("parent_id=?", parentId).Find(&collArr)
	} else {
		err = mysql.Find(&collArr)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: collArr})
}

func newsTypeAdd(c *gin.Context) {
	resDt := &st.NewsType{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	//	mysql.ShowSQL(true)
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()

	err = sess.Begin()
	if err != nil {
		return
	}
	t := time.Now()
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	_, err = sess.Cols("type_name", "parent_id", "type_img", "create_time", "update_time").InsertOne(&st.NewsType{TypeName: resDt.TypeName, ParentId: resDt.ParentId, TypeImg: resDt.TypeImg, CreateTime: t, UpdateTime: t})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "添加" + resDt.TypeName + "成功!"})

}

func newsTypeEdit(c *gin.Context) {
	resDt := &st.NewsType{}
	err := c.BindJSON(resDt)
	if err != nil {
		return
	}
	fmt.Printf("JhVar %+v \r\n", resDt)

	mysql, err := sv.GetEngine()
	// mysql.ShowSQL(true)
	if err != nil {
		c.JSON(409, "")
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return
	}
	_, err = sess.Where("type_id=?", resDt.TypeId).Update(&st.NewsType{TypeName: resDt.TypeName, ParentId: resDt.ParentId, TypeImg: resDt.TypeImg})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(409, err.Error())
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "id:" + strconv.Itoa(resDt.TypeId) + " 编辑成功!"})

}

func newsTypeDel(c *gin.Context) {
	TypeId := c.Query("TypeId")
	mysql, err := sv.GetEngBom()
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "Failed", Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			c.JSON(409, "")
			return
		}
	}(mysql)
	_, err = mysql.Where("type_id=?", TypeId).Delete(&st.NewsType{})
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "Failed", Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "id:" + TypeId + " 删除成功!"})

}
